package com.vtron.dbase.redis;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static com.vtron.dbase.redis.RedisConfig.getBean;

/**
 * 使用redis实现Mybatis的二级缓存，实现Cache接口
 * @date : 2021/12/28 16:02
 * @author: 忻龙彪
 */
public class MybatisRedisCache implements Cache {
    private  final String  SYSDICTYPEMAPPER ="SysDictTypeMapper";
    private  final Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);
    /**
     * 读写锁
     */
    private final ReadWriteLock readWriteLock=new ReentrantReadWriteLock(true);

    private RedisTemplate<String, Object> redisTemplate =  (RedisTemplate<String, Object>) RedisConfig.getBean("redisTemplate");
    private String id;

    public MybatisRedisCache(final String id) {
        if (id==null){
            throw new IllegalArgumentException("缓存实例需要一个id");
        }
        this.id = id;
    }



    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {
        if (value!=null){
            redisTemplate.opsForValue().set(key.toString(),value);
        }
    }

    @Override
    public Object getObject(Object key) {
        try{
            logger.info("Key={}",key);
            if (key!=null){
                Object obj=redisTemplate.opsForValue().get(key.toString());
                return obj;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object removeObject(Object key) {
        try{
            if (key!=null){
                redisTemplate.delete(key.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void clear() {
        try{
            if (SYSDICTYPEMAPPER.equals(this.id)){
                Set<String> keys = redisTemplate.keys("*:" + "SysDictDataMapper" + "*");
                if(!CollectionUtils.isEmpty(keys)){
                    redisTemplate.delete(keys);
                }
            }
            Set<String> keys = redisTemplate.keys("*:" + this.id + "*");
            if(!CollectionUtils.isEmpty(keys)){
                redisTemplate.delete(keys);
            }
        }catch (Exception e){

        }

    }

    @Override
    public int getSize() {
        Long size=(Long)redisTemplate.execute(new RedisCallback<Long>() {

            @Override
            public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
                return redisConnection.dbSize();
            }
        });
        return size.intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }


}
